#! python
# -*- coding: utf-8 -*-

import time
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


def get_token(filepath="gitee"):
    """获取Gitee的Token"""
    if not os.path.exists(filepath):
        home = os.getenv('UserProfile')
        if home is None:
            home = os.getenv('HOME')
        filepath = f'{home}/.config/gitee'
    with open(filepath, encoding='UTF-8') as fd:
        line = fd.readline()
    return line


def get_browser(options=None):
    """return browser"""
    if options is None:
        options = Options()
    driver = webdriver.Edge(options=options)
    return driver


def find_page(driver,
              selector='[@class="icon item" and @rel="next"]',
              parent='//div[@id="git-discover-page"]/child::a',
              **kwargs):
    """ find the link of prev page"""
    xpath = parent + selector
    links = driver.find_elements(By.XPATH, xpath)
    if len(links) == 0:
        return None
    elif len(links) == 1:
        return links[0]
    else:
        return links


def get_repositories(driver,
                     selector='[@class="repository"]',
                     parent='//ul[@id="search-projects-ulist"]/div/h4/span/span/a',
                     timeout=1,
                     **kwargs):
    """ get links for projects in container """
    links = []
    xpath = parent + selector
    driver.implicitly_wait(timeout)
    links = [e.get_property('href') for e in driver.find_elements(By.XPATH, xpath)]
    return links


def goto_next_page(driver,
                   selector='[@class="icon item" and @rel="next"]',
                   parent='//div[@id="git-discover-page"]/child::a',
                   timeout=3,
                   **kwargs):
    """ goto next page """
    try:
        print("goto_next_page")
        link = find_page(driver, selector, parent)
        if link is not None:
            print(f'link to {link.get_property("href")}')
            link.click()
            locator = (By.XPATH, '//*')
            condition = EC.presence_of_all_elements_located(locator)
            return WebDriverWait(driver, timeout).until(condition)
    except:
        # keyboard
        import pdb
        pdb.set_trace()


url='https://gitee.com/BIT_chenxinliang/projects'
driver = get_browser()
selector='[@class="icon item" and @rel="next"]'
parent='//div[@id="git-discover-page"]/child::a'
xpath = parent + selector

def main(url=url, driver=driver, selector=selector, parent=parent, timeout=5, **kwargs):
    """ 登录 """
    if driver is None:
        driver = get_browser()
    driver.get(url)
    xpath = parent + selector
    locator = (By.XPATH, '//*')
    links = driver.find_elements(By.XPATH, xpath)
    repos = []
    while len(links) > 0:
        active_page = find_page(driver, '[@class="item active"]', parent)
        repos = repos + get_repositories(driver)
        print(f"page {active_page.text}: len(links) = {len(links)}")
        links[0].click()
        condition = EC.presence_of_all_elements_located(locator)
        WebDriverWait(driver, timeout).until(condition)
        links = driver.find_elements(By.XPATH, xpath)
    active_page = find_page(driver, '[@class="item active"]')
    repos = repos + get_repositories(driver)
    print(f"page {active_page.text}: len(links) = {len(links)}")
    return repos


if __name__ == '__main__':
    repos = main(url=url, driver=driver)
